package com.mida.app.report.utils;


import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 获取字段名工具类
 */
public class FieldNameUtil {
    /**
     * 获取属性名
     *
     * @param fn
     * @param <T>
     * @return
     */
    public static <T> String getFieldName(com.mida.app.report.utils.SerilizableFunction<T, ?> fn) {

        Method writeReplaceMethod;

        try {
            writeReplaceMethod = fn.getClass().getDeclaredMethod("writeReplace");


        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }


        boolean IsAccessible = writeReplaceMethod.isAccessible();

        writeReplaceMethod.setAccessible(true);

        SerializedLambda serializedLambda;

        try {
            serializedLambda = (SerializedLambda) writeReplaceMethod.invoke(fn);

        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);

        }

        writeReplaceMethod.setAccessible(IsAccessible);


        String fieldName = serializedLambda.getImplMethodName().substring("get".length());

        fieldName = fieldName.replaceFirst(fieldName.charAt(0) + "", (fieldName.charAt(0) + "").toLowerCase());

        Field field;

        try {
            field = Class.forName(serializedLambda.getImplClass().replace("/", ".")).getDeclaredField(fieldName);
        } catch (ClassNotFoundException | NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
        return fieldName;
    }
}
